﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace GW2LastOnline
{
    public partial class formFind : Form
    {
        public delegate void OnFilterChangedEventHandler(string filter);
        public event OnFilterChangedEventHandler OnFilterChanged;

        private DateTime lastKey;
        private bool delaying;
        private string lastFilter;

        public formFind()
        {
            InitializeComponent();
        }

        private void textSearch_KeyDown(object sender, KeyEventArgs e)
        {
            lastKey = DateTime.Now;

            bool delayKey = false;
            lock (this)
            {
                if (!delaying)
                {
                    delaying = true;
                    delayKey = true;
                }
            }

            if (delayKey)
                new Thread(new ThreadStart(delegate
                {
                    while (DateTime.Now.Subtract(lastKey).TotalMilliseconds < 500)
                    {
                        Thread.Sleep(100);
                    }

                    if (lastFilter != textSearch.Text)
                    {
                        lastFilter = textSearch.Text;
                        if (OnFilterChanged != null)
                            OnFilterChanged(lastFilter);
                    }

                    lock (this)
                    {
                        delaying = false;
                    }
                })).Start();
        }

        private void formFind_FormClosing(object sender, FormClosingEventArgs e)
        {
            textSearch.Text = "";
            if (lastFilter != "")
            {
                lastFilter = "";
                if (OnFilterChanged != null)
                    OnFilterChanged(lastFilter);
            }

            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
            }
        }
    }
}
